package com.rt.java.util.concurrent;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

public class AtomicReferenceDemo {
    public static void main(String[] args) throws InterruptedException {
        ARObj arObj = new ARObj("张三", 0);
        AtomicReference<ARObj> ar = new AtomicReference<>(arObj);
        AtomicInteger ai = new AtomicInteger(0);
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        CountDownLatch countDownLatch = new CountDownLatch(3);
        for (int i = 0; i < 3; i++) {
            threadPool.execute(() -> {
                for (int j = 0; j < 10000; j++) {
                    //arObj.setAge(arObj.getAge() + 1);
                    ar.getAndSet(new ARObj("张三", ai.incrementAndGet()));
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        //System.out.println(arObj.getAge());
        System.out.println(ar.get().getAge());
    }
}

@Data
@AllArgsConstructor
class ARObj {
    private String name;
    private int age;
}
